package cn.tedu.lucky.draw.server.controller;

import cn.tedu.lucky.draw.server.common.annotation.OperationLog;
import cn.tedu.lucky.draw.server.common.result.JsonResult;
import cn.tedu.lucky.draw.server.protocol.po.Activity;
import cn.tedu.lucky.draw.server.protocol.po.Prize;
import cn.tedu.lucky.draw.server.protocol.query.ActivityQuery;
import cn.tedu.lucky.draw.server.service.IActivityService;
import org.json.JSONException;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;


@RestController
@CrossOrigin
public class ActivityController {

    @Autowired
    private IActivityService activityService;

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job csvToDBJob;

    @Autowired
    private JobExplorer jobExplorer;

    @PostMapping("/draw/activty/getAll")
    public JsonResult<List<Activity>> getAll(@RequestBody ActivityQuery activityQuery){
        System.out.println(activityQuery);
        return JsonResult.ok(activityService.findAll(activityQuery));

    }

    @OperationLog(operation = "新增活动")
    @PostMapping("/draw/activty/save")
    public JsonResult<Void> saveActivity(@RequestBody Activity activity){
        activityService.save(activity);
        return JsonResult.ok();
    }

    @PostMapping("/draw/activty/{id}")
    public JsonResult<Activity> getActivtyById(@PathVariable Long id){
        Activity activity = activityService.findActivityById(id);
        return JsonResult.ok(activity);
    }

    //http://localhost:8080/activty/csvToDB
    @GetMapping("/activty/csvToDB")
    public String csvToDB() throws Exception{
        JobParameters jobParameters = new JobParametersBuilder(new JobParameters(), jobExplorer)
                .addLong("time", new Date().getTime())//记录当前操作时间
                .getNextJobParameters(csvToDBJob).toJobParameters();//基于提供的Job，获取下一次作业启动时应使用的JobParameters
        JobExecution run = jobLauncher.run(csvToDBJob, jobParameters);
        return run.getId().toString();
    }

    @GetMapping("/app/draw/activity/getAll")
    public JsonResult<List<Activity>> getAll(){
        return JsonResult.ok(
                activityService.findAll()
        );
    }

    @GetMapping("/app/draw/activity/trigger")
    public JsonResult<Prize> Trigger(Long activityId) throws JSONException {
        Prize prize=activityService.trigger(activityId);
        return JsonResult.ok(prize);
    }
}
